import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// import router from '@/router'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
  baseURL: `https://slwl-api.itheima.net`,
  timeout: 5000

})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // console.log(1111)
    if (store.getters.token) {
      config.headers.Authorization = store.getters.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const { data, code } = response.data // 默认json格式
    if (code === 200) {
      return data
    } else {
      new Error('请求成功数据')
    }
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response
  },
  error => {
    console.log(error.response)
    // console.dir(error)
    if (error.response.status === 401) {
      Message({
        message: error.response.data.msg,
        type: 'error',
        duration: 3 * 1000
      })

      // router.push('/login')
    }
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

export default service
